from rest_framework import serializers
from .models import SurveyRecord, SurveyImage, FavoriteLocation

class SurveyImageSerializer(serializers.ModelSerializer):
    compressed_image_url = serializers.SerializerMethodField()
    thumbnail_url = serializers.SerializerMethodField()
    
    class Meta:
        model = SurveyImage
        fields = ['id', 'image', 'compressed_image_url', 'thumbnail_url', 'orientation', 'uploaded_at']
        read_only_fields = ['id', 'uploaded_at', 'compressed_image_url', 'thumbnail_url']
    
    def get_compressed_image_url(self, obj):
        if obj.compressed_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.compressed_image.url)
        return None
    
    def get_thumbnail_url(self, obj):
        if obj.thumbnail:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.thumbnail.url)
        return None

class SurveyRecordSerializer(serializers.ModelSerializer):
    images = SurveyImageSerializer(many=True, read_only=True)
    
    class Meta:
        model = SurveyRecord
        fields = ['id', 'location_name', 'address', 'latitude', 'longitude', 
                 'orientation', 'notes', 'survey_date', 'images', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']

class SurveyRecordCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = SurveyRecord
        fields = ['location_name', 'address', 'latitude', 'longitude', 
                 'orientation', 'notes', 'survey_date']
        
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)

class FavoriteLocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = FavoriteLocation
        fields = ['id', 'name', 'address', 'latitude', 'longitude', 'created_at']
        read_only_fields = ['id', 'created_at']
        
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)